package top.braycep.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import top.braycep.bean.VersionInfo;
import top.braycep.ui.AboutUI;

import java.util.List;

public class UpdateUtils {
    private static final Log logger = LogFactory.get(UpdateUtils.class);

    private static final String defaultReleaseUrl = "https://gitee.com/api/v5/repos/braycep/jar-builder-v3/releases/latest";

    private static final String defaultPath = "cache/";

    private static VersionInfo versionInfo;

    public static boolean hasUpdate() {
        try {
            logger.info("Checking For Update...");
            versionInfo = getNewVersionFromLocal();
            if (versionInfo != null && StrUtil.isNotBlank(versionInfo.getVersionNo()) && !AboutUI.VERSION.equals(versionInfo.getVersionNo())) {
                logger.info("found new version[{}] from cache", versionInfo.getVersionNo());
                return true;
            } else {
                versionInfo = getNewVersionFromRelease();
                if (versionInfo != null && StrUtil.isNotBlank(versionInfo.getVersionNo()) && !AboutUI.VERSION.equals(versionInfo.getVersionNo())) {
                    logger.info("found new version[{}] from release", versionInfo.getVersionNo());
                    return true;
                }
            }
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
        }
        logger.info("not found new version");
        return false;
    }

    /**
     * 从本地缓存获取最新版本
     *
     * @return 新版本编号
     */
    public static VersionInfo getNewVersionFromLocal() {
        boolean exist = FileUtil.exist(defaultPath + "latest");
        if (exist) {
            List<String> lines = FileUtil.readLines(defaultPath + "latest", "UTF8");
            if (!lines.isEmpty()) {
                String firstLine = lines.get(0).trim();
                if (firstLine.matches("(((\\d\\.){2}\\d)(-beta\\.\\d+)?)")) {
                    String filename = "jarbuilder-" + firstLine + ".zip";
                    return buildVersionInfo(firstLine, filename, defaultPath + "/" + filename, null, true);
                }
            }
        }

        return null;
    }

    /**
     * 从发布页获取最新版本
     *
     * @return 新版本编号
     */
    public static VersionInfo getNewVersionFromRelease() {
        String resp = HttpUtil.get(defaultReleaseUrl);
        boolean isJsonObj = JSONUtil.isTypeJSONObject(resp);
        if (isJsonObj) {
            JSONObject rootObj = JSONUtil.parseObj(resp);
            String versionNum = rootObj.getStr("name");
            if (versionNum.matches("(((\\d\\.){2}\\d)(-beta\\.\\d+)?)")) {
                String filename = "jarbuilder-" + versionNum + ".zip";
                JSONArray assets = rootObj.getJSONArray("assets");
                String downloadUrl = null;
                if (!assets.isEmpty()) {
                    downloadUrl = assets.getJSONObject(0).getStr("browser_download_url");
                }
                return buildVersionInfo(versionNum, filename, defaultPath + "/" + filename, downloadUrl, false);
            }
        }
        return null;
    }

    private static VersionInfo buildVersionInfo(String versionNo, String filename, String localPath, String downloadUrl, boolean isFromLocal) {
        VersionInfo v = new VersionInfo();
        v.setVersionNo(versionNo);
        v.setFilename(filename);
        v.setLocalPath(localPath);
        v.setDownloadUrl(downloadUrl);

        v.setReleasePage("https://gitee.com/braycep/jar-builder-v3/releases");

        return v;
    }

    public static VersionInfo getVersionInfo() {
        return versionInfo;
    }
}
